package com.shimmer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Package com.shimmer
 * @Author shimmer
 * @Date 2020/8/15 20:32
 * @TODO
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 防止获取参数中文乱码
        req.setCharacterEncoding("UTF-8");
        // 通过req.getParameter()方法获取页面参数
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        // System.out.println("输入的账户："+name);
        // System.out.println("输入的密码："+password);
        String html;
        if ("shimmer".equals(name)&&"123".equals(password)){
            // html = "<div style='color:green'>登录成功</div>";
            // 服务端跳转
            req.getRequestDispatcher("success.html").forward(req,resp);
        }else{
            // html = "<div style='color:red'>登录失败</div>";
            // 客户端跳转
            resp.sendRedirect("fail.html");
        }
        // 防止返回参数中文乱码
        resp.setContentType("text/html; charset=UTF-8");
        // resp.getWriter().println(html);
    }
    
    //在执行doGet和doPost方法之前，先执行service()方法进行判断
    // @Override
    // public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    //     System.out.println("执行了service方法");
    //     String name = req.getParameter("name");
    //     String password = req.getParameter("password");
    //
    //     // System.out.println("输入的账户："+name);
    //     // System.out.println("输入的密码："+password);
    //     String html;
    //     if ("shimmer".equals(name)&&"123".equals(password)){
    //         html = "<div style='color:green'>successful</div>";
    //     }else{
    //         html = "<div style='color:red'>fail</div>";
    //     }
    //     res.getWriter().println(html);
    // }

    public LoginServlet() {
        System.out.println("创建LoginServlet实例");
    }
}
